package top.zackyoung.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import top.zackyoung.demo.entity.User;
import top.zackyoung.demo.service.JpaService;

import java.util.stream.Stream;

/**
 * @author: ZackYoung
 * @time: 2020/9/14
 */

@RestController
public class JpaController {

    @Autowired
    JpaService jpaService;

    /**
     * jpa使用hibernate添加操作
     */
    @GetMapping(path = "/add")
    public String addNewUser1(@RequestParam String name) {
        User user = new User();
        user.setUserName(name);
        return jpaService.add1(user);
    }

    /**
     * 自定义删除数据ById
     */
    @RequestMapping("/delete/{id}")
    public String deleteById(@PathVariable Long id) {
        int delete = jpaService.delete(id);
        return result(delete);
    }

    /**
     * 使用自定义添加操作
     */
    @RequestMapping("/add2")
    public String addNewUser2(@RequestParam String name, @RequestParam Long id) {
        int i = jpaService.add2(id, name);
        return result(i);
    }

    /**
     * jpa查询操作
     */
    @GetMapping(path = "/all")
    @Cacheable(value = "getAllUsers")
    public Iterable<User> getAllUsers() {
        return jpaService.getAllUsers();
    }

    /**
     * 自定义通过name查找
     */
    @RequestMapping("/query/{name}")
    public User getByNameUser(@PathVariable String name){
        return jpaService.getByNameUser(name);
    }

    /**
     * jpa修改操作
     */
    @GetMapping("/update")
    public String update(@RequestParam String name, @RequestParam Long id) {
        int i = jpaService.updateByUserId(id, name);
        return result(i);
    }

    /**
     * 分页查询功能
     */
    @RequestMapping(value = "/test1")
    public Stream<User> findAllOrder(@RequestParam("roleId") Long roleId, @RequestParam("page") Integer page){
        return jpaService.findAllOrder(roleId, page);
    }

    public String result(int result) {
        if (result > 0) {
            return "操作成功";
        }
        return "操作失败";
    }
}
